package org.jxf.gps.jt808.server;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jxf.gps.jt808.message.JT808FrameDecoder;
import org.jxf.gps.jt808.message.MsgHandle;
import org.jxf.gps.jt808.message.ShowLogFrameDecoder;

import com.jfinal.plugin.IPlugin;

public class ServerPlugin implements IPlugin {
	private static Logger logger = Logger.getLogger(ServerPlugin.class);
	public boolean start() {
		logger.info("ServerPlugin start !!!");
		
		//1、创建channelfactory
//		ChannelFactory channelFactory = new NioServerSocketChannelFactory(Executors
//				.newCachedThreadPool(), Executors.newCachedThreadPool(),16);
		ChannelFactory channelFactory = new NioServerSocketChannelFactory(Executors
				.newCachedThreadPool(), Executors.newCachedThreadPool());//默认线程数为cpu core的2倍

		//2、根据channelfactory创建Server
		ServerBootstrap bootstrap = new ServerBootstrap(channelFactory);
		
		//3、通过Server取pipeline
		ChannelPipeline pipeline = bootstrap.getPipeline();
		
		//4、创建Handler
		ServerHandler handler = new ServerHandler();
		
		//5、为pipeline添加handler
		pipeline.addLast("0", new ShowLogFrameDecoder());//记录原始包
		pipeline.addLast("1", new JT808FrameDecoder());//如果粘包将会按0x7E作为起止分隔符，分成多各包，多次调用handle的messageReceived方法
		pipeline.addLast("2", handler);

//        pipeline.addLast("decoder", new StringDecoder());
//        pipeline.addLast("encoder", new StringEncoder());
		
		//6、设置Server的参数
		bootstrap.setOption("child.tcpNoDelay", true);
		bootstrap.setOption("child.keepAlive", true);

		//7、绑定IP和端口，启动服务
		Channel channel = bootstrap.bind(new InetSocketAddress(59090));		
		//Channel channel = bootstrap.bind(new InetSocketAddress(9001));
		
		return true;
	}

	public boolean stop() {
		logger.info("ServerPlugin stop !!!");
		return true;
	}

}
